package com.zxp.utils.linEnvUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Utility class for managing Linux system environment variables.
 */
public class EnvUtils {

    public static void main(String[] args) {
        try {
            // Example: Modify an existing variable named MY_VARIABLE
            modifyOrAddSystemEnvironmentVariable("MY_VARIABLE", "new_value");

            // Example: Add a new variable named NEW_VARIABLE
            modifyOrAddSystemEnvironmentVariable("NEW_VARIABLE", "new_value");

            // Example: Delete an existing variable named OLD_VARIABLE
            deleteSystemEnvironmentVariable("OLD_VARIABLE");

            // Example: Query the value of an existing variable named EXISTING_VARIABLE
            String value = querySystemEnvironmentVariable("EXISTING_VARIABLE");
            System.out.println("Value of EXISTING_VARIABLE: " + value);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * Modifies an existing Linux system environment variable or adds a new one if it doesn't exist.
     *
     * @param variableName  The name of the variable to be modified or added.
     * @param variableValue The new value for the variable.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void modifyOrAddSystemEnvironmentVariable(String variableName, String variableValue)
            throws IOException, InterruptedException {
        if (querySystemEnvironmentVariable(variableName) == null) {
            // Variable doesn't exist, add it
            addSystemEnvironmentVariable(variableName, variableValue);
        } else {
            // Variable exists, modify it
            modifySystemEnvironmentVariable(variableName, variableValue);
        }
    }

    /**
     * Modifies an existing Linux system environment variable.
     *
     * @param variableName  The name of the variable to be modified.
     * @param variableValue The new value for the variable.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void modifySystemEnvironmentVariable(String variableName, String variableValue)
            throws IOException, InterruptedException {
        // Build the export command for modification
        String command = "export " + variableName + "=" + variableValue;

        // Execute the command
        executeCommand(command);
    }

    /**
     * Adds a new Linux system environment variable.
     *
     * @param variableName  The name of the new variable.
     * @param variableValue The value for the new variable.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void addSystemEnvironmentVariable(String variableName, String variableValue)
            throws IOException, InterruptedException {
        // Build the export command for addition
        String command = "export " + variableName + "=" + variableValue;

        // Execute the command
        executeCommand(command);
    }

    /**
     * Deletes an existing Linux system environment variable.
     *
     * @param variableName The name of the variable to be deleted.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void deleteSystemEnvironmentVariable(String variableName)
            throws IOException, InterruptedException {
        // Check if the variable exists before attempting deletion
        if (querySystemEnvironmentVariable(variableName) != null) {
            // Variable exists, proceed with deletion
            String command = "unset " + variableName;
            executeCommand(command);
        } else {
            // Variable doesn't exist, throw an error
            throw new RuntimeException("Variable does not exist: " + variableName);
        }
    }

    /**
     * Queries the value of an existing Linux system environment variable.
     *
     * @param variableName The name of the variable to query.
     * @return The value of the variable, or null if the variable does not exist.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static String querySystemEnvironmentVariable(String variableName)
            throws IOException, InterruptedException {
        // Build the echo command for querying
        String command = "echo $" + variableName;

        // Execute the command and capture the output
        Process process = new ProcessBuilder("bash", "-c", command).start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = reader.readLine();

        return line != null ? line.trim() : null;
    }

    /**
     * Executes a command using ProcessBuilder.
     *
     * @param command The command to execute.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    private static void executeCommand(String command) throws IOException, InterruptedException {
        // Create a ProcessBuilder object
        ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", command);

        // Start the process and wait for it to complete
        Process process = processBuilder.start();
        int exitCode = process.waitFor();

        // Check if the command was executed successfully
        if (exitCode != 0) {
            throw new RuntimeException("Command execution failed. Exit code: " + exitCode);
        }
    }
}
